package message

import (
	"context"
	"errors"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/utils/verifycode"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/message/sms_code"
	pb "git.mycaigou.com/gfyx/micro-gfyx-user-service/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service"
	"git.myscrm.cn/golang/stark/v4"
	"regexp"
	"time"
)

const (
	TENANT_INFO_CACHE_KEY            = "gfyx:user_service:tenant_list:"
	TENANT_NAME_CACHE_KEY            = "gfyx:user_service:tenant_name_md5:"
	TENANT_NAME_EMPTY_VALUE          = "empty"
	TENANT_PROFIT_CACHE_KEY          = "gfyx:user_service:tenant_profit:"
	TENANT_PROFIT_CACHE_KEY_TIME_OUT = 60 * 2
)

type UserInfoService struct {
	smsCodeRepo sms_code.SmsCodeRepositoryIface
}

func NewVerifyCodeService(
	smsCodeRepo sms_code.SmsCodeRepositoryIface,
) VerifyCodeServiceIface {
	return &UserInfoService{
		smsCodeRepo: smsCodeRepo,
	}
}

// SendSmsCode 发送验证码
func (s *UserInfoService) SendSmsCode(ctx context.Context, request *pb.SendSmsRequest) (*pb.SendSmsResponse, error) {
	// 发送验证码（手机号验证码验证）
	if regexp.MustCompile("^1[345789]{1}\\\\d{9}$").MatchString(request.Mobile) {
		return nil, errors.New("请输入合法的手机号码")
	}

	code, err := verifycode.NewVerifyCode(ctx).SendSMS(request.Mobile)
	if err != nil {
		stark.Logger.Errorf(ctx, "NewVerifyCode SendSMS error:%+v", err)
		return nil, errors.New("发送短信失败，请稍后重试")
	}

	// 保存记录
	record := &sms_code.SmsCodePo{
		Mobile:     request.Mobile,
		Scene:      request.Scene,
		Code:       code,
		SendTime:   time.Now(),
		CreatedOn:  time.Now(),
		CreatedBy:  "",
		ModifiedOn: time.Now(),
		ModifiedBy: "",
		IsDeleted:  0,
	}

	_, err = s.smsCodeRepo.SaveSmsCode(ctx, record)
	if err != nil {
		stark.Logger.Errorf(ctx, "SaveSmsCode error:%+v", err)
		return nil, errors.New("保存发送记录失败")
	}

	return &pb.SendSmsResponse{
		Success: true,
	}, nil
}
